import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import { Link } from 'react-router-dom';
import {
  PlusIcon,
  MagnifyingGlassIcon,
  UserGroupIcon,
  UserIcon,
  CalendarIcon,
  FolderIcon,
  Cog6ToothIcon,
} from '@heroicons/react/24/outline';
import api from '../services/api';
import LoadingSpinner from '../components/LoadingSpinner';
import toast from 'react-hot-toast';

const Teams = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const queryClient = useQueryClient();

  // 获取团队列表
  const { data: teamsData, isLoading } = useQuery(
    ['teams', searchTerm],
    () => api.get('/teams', { params: { search: searchTerm } }),
    {
      keepPreviousData: true,
    }
  );

  // 离开团队
  const leaveTeamMutation = useMutation(
    (teamId) => api.delete(`/teams/${teamId}/leave`),
    {
      onSuccess: () => {
        queryClient.invalidateQueries('teams');
        toast.success('已离开团队');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '操作失败');
      },
    }
  );

  const handleLeaveTeam = (teamId, teamName) => {
    if (window.confirm(`确定要离开团队 "${teamName}" 吗？`)) {
      leaveTeamMutation.mutate(teamId);
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return '未知';
    return new Date(dateString).toLocaleDateString();
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="lg" />
      </div>
    );
  }

  const teams = teamsData?.data?.teams || [];

  return (
    <div className="space-y-6">
      {/* 页面标题和操作 */}
      <div className="sm:flex sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">团队管理</h1>
          <p className="mt-1 text-sm text-gray-500">
            管理您的团队，邀请成员协作
          </p>
        </div>
        <div className="mt-4 sm:mt-0">
          <Link
            to="/teams/new"
            className="btn-primary"
          >
            <PlusIcon className="h-4 w-4 mr-2" />
            创建团队
          </Link>
        </div>
      </div>

      {/* 搜索 */}
      <div className="card">
        <div className="card-body">
          <div className="max-w-lg">
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" />
              </div>
              <input
                type="text"
                placeholder="搜索团队..."
                className="input pl-10"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
        </div>
      </div>

      {/* 团队列表 */}
      {teams.length > 0 ? (
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          {teams.map((team) => (
            <div key={team.id} className="card hover:shadow-md transition-shadow duration-200">
              <div className="card-body">
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center space-x-3">
                      <UserGroupIcon className="h-8 w-8 text-primary-600 flex-shrink-0" />
                      <div className="flex-1 min-w-0">
                        <h3 className="text-lg font-medium text-gray-900 truncate">
                          {team.name}
                        </h3>
                        <p className="text-sm text-gray-500 truncate">
                          {team.description || '无描述'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>

                {/* 团队统计 */}
                <div className="mt-4 space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">成员数量</span>
                    <span className="font-medium text-gray-900">
                      {team.member_count || 0} 人
                    </span>
                  </div>
                  
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-500">项目数量</span>
                    <span className="font-medium text-gray-900">
                      {team.project_count || 0} 个
                    </span>
                  </div>

                  <div className="flex items-center justify-between text-sm text-gray-500">
                    <div className="flex items-center">
                      <CalendarIcon className="h-4 w-4 mr-1" />
                      <span>创建于 {formatDate(team.created_at)}</span>
                    </div>
                  </div>
                </div>

                {/* 团队成员预览 */}
                {team.members && team.members.length > 0 && (
                  <div className="mt-4">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-700">团队成员</span>
                      <span className="text-sm text-gray-500">
                        {team.members.length} 人
                      </span>
                    </div>
                    <div className="mt-2 flex -space-x-2">
                      {team.members.slice(0, 5).map((member, index) => (
                        <div
                          key={member.id}
                          className="h-8 w-8 rounded-full bg-primary-500 flex items-center justify-center text-white text-xs font-medium border-2 border-white"
                          title={member.username}
                        >
                          {member.username.charAt(0).toUpperCase()}
                        </div>
                      ))}
                      {team.members.length > 5 && (
                        <div className="h-8 w-8 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 text-xs font-medium border-2 border-white">
                          +{team.members.length - 5}
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* 操作按钮 */}
                <div className="mt-4 flex items-center justify-between">
                  <div className="flex space-x-2">
                    <Link
                      to={`/teams/${team.id}`}
                      className="btn-outline text-sm"
                    >
                      查看详情
                    </Link>
                    <Link
                      to={`/teams/${team.id}/projects`}
                      className="btn-outline text-sm"
                    >
                      管理项目
                    </Link>
                  </div>
                  <div className="flex items-center space-x-2">
                    {team.role === 'owner' ? (
                      <Link
                        to={`/teams/${team.id}/edit`}
                        className="text-primary-600 hover:text-primary-700"
                        title="管理团队"
                      >
                        <Cog6ToothIcon className="h-4 w-4" />
                      </Link>
                    ) : (
                      <button
                        onClick={() => handleLeaveTeam(team.id, team.name)}
                        className="text-danger-600 hover:text-danger-700"
                        title="离开团队"
                      >
                        <UserIcon className="h-4 w-4" />
                      </button>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="card">
          <div className="card-body text-center py-12">
            <UserGroupIcon className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">暂无团队</h3>
            <p className="mt-1 text-sm text-gray-500">开始创建您的第一个团队吧！</p>
            <div className="mt-6">
              <Link to="/teams/new" className="btn-primary">
                创建团队
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Teams;
